<?php

namespace addons\Merchants\merchant\modules\common\controllers;

use Yii;
use yii\web\NotFoundHttpException;
use common\traits\Curd;
use common\models\base\SearchModel;
use common\enums\StatusEnum;
use common\models\rbac\AuthItem;
use common\models\rbac\AuthItemChild;
use addons\Merchants\common\models\Addons;
use addons\Merchants\merchant\controllers\BaseController;
use addons\Flow\common\models\Metadata;
use addons\Flow\common\models\Status;
use addons\Flow\common\models\Transition;
use addons\Flow\common\models\Workflow;
/**
 * Class AddonsController
 * @package merchant\modules\common\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class AddonsController extends BaseController
{
    use Curd;

    /**
     */
    public $modelClass = Workflow::class;

    /**
     * 首页
     *
     * @return mixed|string
     * @throws NotFoundHttpException
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => Addons::class,
            'scenario' => 'default',
            'partialMatchAttributes' => ['title', 'name'], // 模糊查询
            'defaultOrder' => [
                'title_initial' => SORT_ASC,

            ],
            'pageSize' => $this->pageSize,
        ]);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andWhere(['status'=>StatusEnum::ENABLED,'merchant_id'=>Yii::$app->user->identity->merchant_id]);
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'addonsGroup' => Yii::$app->params['addonsGroup'],
        ]);
    }

    /**
     * 卸载
     *
     * @return mixed
     * @throws NotFoundHttpException
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionUnInstall()
    {
        $request = Yii::$app->request;

        $addons = \common\models\common\Addons::find()->select('*')
            ->where(['name' => $request->get('name')])
            ->one();
        if($addons->group =='approve') {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                //卸载工作流
                Workflow::deleteAll(['id' => $request->get('name'), 'merchant_id' => Yii::$app->user->identity->merchant_id]);
                Status::deleteAll(['workflow_id' => $request->get('name'), 'merchant_id' => Yii::$app->user->identity->merchant_id]);
                Transition::deleteAll(['workflow_id' => $request->get('name'), 'merchant_id' => Yii::$app->user->identity->merchant_id]);
                Metadata::deleteAll(['workflow_id' => $request->get('name'), 'merchant_id' => Yii::$app->user->identity->merchant_id]);
//            $models = 'addons\Repair\common\models\Repair';
//            Repair::deleteAll(['workflow_id' => $request->get('name'), 'merchant_id' => Yii::$app->user->identity->merchant_id]);
                // 删除数据库
                if ($model = Addons::findOne(['name' => $request->get('name'),'merchant_id'=>Yii::$app->user->identity->merchant_id])) {
                    $model->delete();
                }
                $transaction->commit();
                return $this->message("卸载成功", $this->redirect(['index']));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return (Yii::$app->request->referrer);
            }
        }
        else{
            $transaction = Yii::$app->db->beginTransaction();
            // 删除数据库
            try {
                if ($model = Addons::findOne(['name' => $request->get('name'), 'merchant_id' => Yii::$app->user->identity->merchant_id])) {
                    $model->delete();
                }
                $transaction->commit();
                return $this->message("卸载成功", $this->redirect(['index']));
            }catch (\Exception $e) {
                $transaction->rollBack();
                return (Yii::$app->request->referrer);
            }
        }
    }

    /**
     * 安装列表
     *
     * @return mixed|string
     * @throws \Throwable
     * @throws \yii\db\Exception
     */
    public function actionLocal()
    {
        return $this->render($this->action->id, [
//            'list' => Yii::$app->services->merchantAddons->getLocalList(),
            'list' => Yii::$app->merchantsService->addons->getLocalList(),

        ]);
    }

    /**
     * 安装
     *
     * @return mixed|string
     * @throws \Throwable
     * @throws \yii\db\Exception
     */
    public function actionInstall($installData = true)
    {
        $request = Yii::$app->request;

        if (!($class = Yii::$app->services->addons->getConfigClass($request->get('name')))) {
            return $this->message('实例化失败,插件不存在或检查插件名称', $this->redirect(['index']), 'error');
        }

        ini_set("max_execution_time", 300);

        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $config = new $class;
            // 更新插件信息
            Yii::$app->services->merchantAddons->update($request->get('name'), $config);
            // 批量写入权限
            $items = AuthItem::find()
                ->where(['status' => StatusEnum::ENABLED])
                ->andWhere(['app_id' => 'merchant','addons_name'=>$request->get('name')])
                ->select(['id', 'title', 'name', 'pid', 'level', 'app_id', 'is_addon', 'addons_name'])
                ->orderBy('sort asc, id asc')
                ->asArray()
                ->all();
            foreach ($items as $value) {
                $rows[] = [
                    Yii::$app->user->identity->role_id,
                    $value['id'],
                    $value['name'],
                    $value['app_id'],
                    $value['is_addon'],
                    $value['addons_name'],
                ];
            }
            $field = ['role_id', 'item_id', 'name', 'app_id', 'is_addon', 'addons_name'];
            !empty($rows) && Yii::$app->db->createCommand()->batchInsert(AuthItemChild::tableName(), $field, $rows)->execute();

            //安装工作流
            $addons = \common\models\common\Addons::find()->select('*')
                ->where(['name' => $request->get('name')])
                ->one();
            if($addons->group =='approve') {
                //安装流程
                $model = $this->findModel($request->get('name'));
                $model->merchant_id = Yii::$app->user->identity->merchant_id;
                $model->title = $request->get('title');
                $model->id = $request->get('name');
                $model->initial_status_id = 'apply';
                if (!$model->save()) {
                    throw new NotFoundHttpException('安装流程失败');
                }
                //初始化流程状态
                $list = ['apply' => '申请', 'audit' => '审核', 'agree' => '通过', 'refused' => '拒绝'];
                $i=0;
                foreach ($list as $id => $label) {
                    $status = new Status();
                    $status->workflow_id = Yii::$app->request->get('name');
                    $status->merchant_id = Yii::$app->user->identity->merchant_id;
                    $status->label = $label;
                    $status->sort = ++$i;
                    $status->id = $id;
                    if (!$status->save()) {
                        throw new NotFoundHttpException('初始化流程状态失败');
                    }
                }
                //初始化工作流转
                $list = ['apply/audit', 'apply/refused', 'audit/agree', 'audit/refused'];
                foreach ($list as $value) {
                    $transition = new Transition();
                    $transition->workflow_id = Yii::$app->request->get('name');
                    $transition->merchant_id = Yii::$app->user->identity->merchant_id;
                    $transition->start_status_id = explode('/', $value)[0];;
                    $transition->end_status_id = explode('/', $value)[1];
                    if (!$transition->save()) {
                        throw new NotFoundHttpException('初始化工作流转失败');
                    }
                }
            }
            $transaction->commit();

            return $this->message('安装/更新成功', $this->redirect(['index']));
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->message($e->getMessage(), $this->redirect(['index']), 'error');
        }

    }
    protected function findModel($id)
    {
        if (empty($id) || empty(($model = $this->modelClass::find()->andWhere(['id' => $id, 'merchant_id' => $this->getMerchantId()])->one()))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }
        return $model;
    }



}